package org.openfans.feed;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.openfans.domain.Article;
import org.openfans.domain.Facade;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;

public class FeedWriter {
	private Facade facade;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public SyndFeed getFeed(String name) {
		SyndFeed aggrFeed = new SyndFeedImpl();
		aggrFeed.setFeedType("rss_2.0");

		aggrFeed.setTitle("openfans - " + name);
		aggrFeed.setLink("http://www.openfans.net/user/" + name);
		aggrFeed.setDescription("RSS at openfans.net");

		List<SyndEntry> entries = new ArrayList<SyndEntry>();
		SyndEntry entry;
		SyndContent description;

		for (Iterator iter = facade.getUserArticle(name).iterator(); iter
				.hasNext();) {
			Article ar = (Article) iter.next();

			entry = new SyndEntryImpl();
			entry.setTitle(ar.getTitle());
			entry.setLink("http://www.openfans.net/viewArticle/"
					+ ar.getArticleId());
			entry.setAuthor(name);
			description = new SyndContentImpl();
			description.setType("text/plain");
			description.setValue(ar.getContent());
			entry.setDescription(description);
			entry.setPublishedDate(ar.getSubmitDate());
			entries.add(entry);

		}
		aggrFeed.setEntries(entries);

		return aggrFeed;
	}
}
